<?php
App::uses('AppController', 'Controller');

class LoginController extends AppController {

	public $components = array("Session");
	public $name = "Login";
	public $uses = array("Sesion");
	
	public function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->allow('logout');
	}
	
	public function login(){
		if ($this->Auth->loggedIn()){
			$this->redirect($this->Auth->loginRedirect);
		}

		if ($this->request->is('post')){
			if ($this->Auth->login()){
				$this->redirect($this->Auth->loginRedirect);
			}
			else{
				$this->Session->setFlash('Usuario o Clave incorrectos. Favor volver a intentar');
			}
		}
	}
	
	public function logout(){
		$SesionId = $this->Session->read('SesionId');
		if(isset($SesionId)||$SesionId!==null){
			$sesion = $this->Sesion->find('first',array(
				'conditions' => array('Sesion.id_sesion' => $SesionId)
			));
			if(!empty($sesion)){        
				$sesion['Sesion']['fecha_fin_sesion'] = date('Y/m/j H:i:s');
				$this->Sesion->save($sesion, false);
				$this->Session->delete('SesionId');
			}
		}
		$this->redirect($this->Auth->logout());
	}
}
?>